// 云函数入口文件
const cloud = require('wx-server-sdk')
const { WXMINIUser } = require('wx-js-utils')
const axios = require('axios')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

// 云函数入口函数
exports.main = async event => {
  const { OPENID: _openid } = cloud.getWXContext()
  if (!_openid) {
    throw new Error('no openid')
  }

  const { orderId } = event
  if (!orderId) {
    throw new Error('no orderId')
  }

  const {
    data: [uData],
  } = await db.collection('store').where({ _openid }).get()
  if (!uData) {
    throw new Error('no login store')
  }

  const {
    data: [{ appId, secret, env }],
  } = await db.collection('config').get()
  const wXMINIUser = new WXMINIUser({ appId, secret })
  const token = await wXMINIUser.getCacheAccessToken()

  const createAt = new Date()

  let {
    data: { errcode, errmsg, resp_data: oData },
  } = await axios.post(
    'https://api.weixin.qq.com/tcb/invokecloudfunction',
    { _id: orderId },
    { params: { access_token: token, env, name: 'list-order' } }
  )
  if (errcode) {
    throw new Error(errmsg)
  }
  ;[oData] = JSON.parse(oData)
  if (!oData) {
    throw new Error('invalid qrcode')
  }
  if (oData.promotionCast.promotion.store._id !== uData._id) {
    throw new Error('different provider')
  }
  if (oData.status !== 1) {
    throw new Error('incorrect status')
  }
  if (oData.checkin && new Date(oData.checkin.createBefore) <= createAt) {
    throw new Error('order expired')
  }

  const {
    data: { modified },
  } = await axios.post(
    'https://api.weixin.qq.com/tcb/databaseupdate',
    {
      env,
      query: `
        db.collection('order')
          .doc('${orderId}')
          .update({
            data: {
              status: 2,
              checkin: { createAt: db.serverDate() },
            },
          })
      `,
    },
    { params: { access_token: token } }
  )
  if (!modified) {
    throw new Error('checkin failed')
  }

  oData.status = 2
  oData.checkin.createAt = createAt

  return oData
}
